package cn.iocoder.yudao.module.handguard.service.orderprocessrecord;

import cn.iocoder.yudao.module.handguard.controller.admin.orderprocessrecord.vo.FlowRecordVO;
import cn.iocoder.yudao.module.handguard.controller.admin.orderprocessrecord.vo.OrderRecordInfoVO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationrecord.ApplicationRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.processrecord.ProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.usertablesaudit.UserTablesAuditDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.applicationrecord.ApplicationRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.processrecord.ProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.usertablesaudit.UserTablesAuditMapper;
import cn.iocoder.yudao.module.handguard.tool.DataConversionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.handguard.controller.app.orderprocessrecord.vo.*;
import cn.iocoder.yudao.module.handguard.dal.dataobject.orderprocessrecord.OrderProcessRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.handguard.convert.orderprocessrecord.OrderProcessRecordConvert;
import cn.iocoder.yudao.module.handguard.dal.mysql.orderprocessrecord.OrderProcessRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.handguard.enums.ErrorCodeConstants.*;

/**
 * 订单审核流程记录 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class OrderProcessRecordServiceImpl implements OrderProcessRecordService {

    @Resource
    private OrderProcessRecordMapper orderProcessRecordMapper;

    @Resource
    private ApplicationRecordMapper applicationRecordMapper;

    @Resource
    private ProcessRecordMapper processRecordMapper;

    @Resource
    private OrderMapper orderMapper;


    @Override
    public Long createOrderProcessRecord(OrderProcessRecordCreateReqVO createReqVO) {

        if("2".equals(createReqVO.getIsFail())){
            if(StringUtils.isBlank(createReqVO.getCauseOfFailure())){
                throw exception(CAUSE_OF_FAILURE_NOT_EXISTS);
            }
        }

        //先删除后插入
        processRecordMapper.deleteProcessRecordById(createReqVO.getOrderApplicationId());

        //订单
        ApplicationRecordDO recordDO = applicationRecordMapper.selectById(createReqVO.getOrderApplicationId());
        // 插入
        ProcessRecordDO processRecordDO = new ProcessRecordDO();
        processRecordDO.setApplicationId(recordDO.getId());
        processRecordDO.setCauseOfFailure(createReqVO.getCauseOfFailure());
        int flow = Integer.valueOf(createReqVO.getFlowN());
        if (flow<=12 && !createReqVO.getIsFail().equals("2")){
            flow = flow+1;
            processRecordDO.setFlowN(String.valueOf(flow));
            processRecordDO.setIsFail("0");
            recordDO.setFlowN(String.valueOf(flow));
        }else {
            processRecordDO.setFlowN(String.valueOf(flow));
            processRecordDO.setIsFail("2");
            recordDO.setApplyState("0");
            recordDO.setFlowN(createReqVO.getFlowN());
        }

        applicationRecordMapper.updateById(recordDO);

        if (flow==13){
            //如果流程13
            processRecordDO.setIsFail("1");
        }
        processRecordDO.setUserId(recordDO.getUserId());
        processRecordMapper.insert(processRecordDO);
        // 返回
        return 1l;
    }

    @Override
    public void updateOrderProcessRecord(OrderProcessRecordUpdateReqVO updateReqVO) {
        // 校验存在
        validateOrderProcessRecordExists(updateReqVO.getId());
        // 更新
        OrderProcessRecordDO updateObj = OrderProcessRecordConvert.INSTANCE.convert(updateReqVO);
        orderProcessRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteOrderProcessRecord(Long id) {
        // 校验存在
        validateOrderProcessRecordExists(id);
        // 删除
        orderProcessRecordMapper.deleteById(id);
    }

    private void validateOrderProcessRecordExists(Long id) {
        if (orderProcessRecordMapper.selectById(id) == null) {
            throw exception(ORDER_PROCESS_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public OrderProcessRecordDO getOrderProcessRecord(Long id) {
        return orderProcessRecordMapper.selectById(id);
    }

    @Override
    public List<OrderProcessRecordDO> getOrderProcessRecordList(Collection<Long> ids) {
        return orderProcessRecordMapper.selectBatchIds(ids);
    }

    @Override
    public List<OrderProcessRecordDO> getOrderProcessRecordList(Long orderId) {
        return orderProcessRecordMapper.selectList(new LambdaQueryWrapper<OrderProcessRecordDO>()
                .eq(OrderProcessRecordDO::getOrderApplicationId, orderId));
    }

    @Override
    public PageResult<OrderProcessRecordDO> getOrderProcessRecordPage(OrderProcessRecordPageReqVO pageReqVO) {
        return orderProcessRecordMapper.selectPage(pageReqVO);
    }

    @Override
    public List<OrderProcessRecordDO> getOrderProcessRecordList(OrderProcessRecordExportReqVO exportReqVO) {
        return orderProcessRecordMapper.selectList(exportReqVO);
    }


    @Override
    public  Map<String,List<OrderProcessRecordRespVO>>  getOrderProcessRecordListById(Long id) {

        List<OrderProcessRecordDO> recordDOList = new ArrayList<>();
        LambdaQueryWrapper<OrderProcessRecordDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderProcessRecordDO::getOrderApplicationId,id);
        wrapper.orderByAsc(OrderProcessRecordDO::getFlowN,OrderProcessRecordDO::getCreateTime);
        recordDOList = orderProcessRecordMapper.selectList(wrapper);

        //只取最新一条
        for(int i=1;i<9;i++){
            wrapper.eq(OrderProcessRecordDO::getOrderApplicationId,id);
            wrapper.eq(OrderProcessRecordDO::getFlowN,String.valueOf(i));
            wrapper.orderByDesc(OrderProcessRecordDO::getCreateTime);
            OrderProcessRecordDO recordDO = orderProcessRecordMapper.selectOne(wrapper);
            if (recordDO!=null){
                recordDOList.add(recordDO);
            }
        }

        Map<String,List<OrderProcessRecordRespVO>> map = new HashMap<>();
        List<OrderProcessRecordRespVO> voList = OrderProcessRecordConvert.INSTANCE.convertList(recordDOList);
        if (voList.size()>0){
            map = DataConversionUtils.groupOrderProcessByStream(voList);
        }

        return map;
    }

    @Override
    public OrderRecordInfoVO getOrderInfo(Long id) {
        BigDecimal practicalAmount = new BigDecimal(0.0);
        OrderRecordInfoVO infoVO = new OrderRecordInfoVO();
        ApplicationRecordDO orderDO = applicationRecordMapper.selectById(id);
        infoVO.setFlowN(orderDO.getFlowN());
        infoVO.setApplyState(orderDO.getApplyState());
        ProcessRecordDO processRecordDO = processRecordMapper.selectOne("application_id",id);
        List<FlowRecordVO> flowRecordVOS = new ArrayList<>();
        if (orderDO!=null){
            if (orderDO.getPracticalAmount()!=null){
                practicalAmount = orderDO.getPracticalAmount();
            }
            String flowName = "完善资料,下放额度,申请贷款,业务员处理,权证处理,资料审核,银行面签填贷款申请表,考察抵押物和经营场所,银行出批复,银行面签抵押合同和借款合同,办理抵押,办公证,放款";
            String [] flowArr = flowName.split(",");
            int num = Integer.valueOf(orderDO.getFlowN());
            for (int i=0;i<flowArr.length;i++) {
                int ii = i+1;
                FlowRecordVO flowRecordVO = new FlowRecordVO();
                flowRecordVO.setFName(flowArr[i]);
                if(ii == num){
                    if (processRecordDO.getIsFail().equals("0")){
                        flowRecordVO.setDescription("待审核");
                    }else if (processRecordDO.getIsFail().equals("1")){
                        flowRecordVO.setDescription("通过");
                    }else if (processRecordDO.getIsFail().equals("2")){
                        flowRecordVO.setDescription(processRecordDO.getCauseOfFailure());
                    }
                }else {
                    if (ii>num){
                        //flowRecordVO.setDescription("审核中");
                    }else {
                        flowRecordVO.setDescription("通过");
                    }
                }
                flowRecordVOS.add(flowRecordVO);
            }
        }
        infoVO.setFlow(flowRecordVOS);
        infoVO.setAmount(practicalAmount);
        return infoVO;
    }






}
